package com.atguigu.schedule.controller;

import com.atguigu.schedule.common.Result;
import com.atguigu.schedule.common.ResultCodeEnum;
import com.atguigu.schedule.pojo.SysUser;
import com.atguigu.schedule.service.SysUserService;
import com.atguigu.schedule.service.impl.SysUserServiceimpl;
import com.atguigu.schedule.util.MD5Util;
import com.atguigu.schedule.util.WebUtil;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.val;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;


@WebServlet("/user/*")
public class SysUserController extends BashController {
    private static SysUserService userService = new SysUserServiceimpl();

    /**
     * 接收用户注册的业务处理方法
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */

    protected void checkUsername(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        SysUser sysUser = userService.findByUsername(username);
        Result result = Result.ok(null);
        if (sysUser != null) {
            result = Result.build(null, ResultCodeEnum.USERNAME_USED);
        }
        WebUtil.writeJson(resp, result);
    }

    protected void regist(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //接受用户参数
        SysUser registUser = WebUtil.readJson(req, SysUser.class);
        //注册进入数据库
        int rows = userService.regist(registUser);
        System.out.println(rows);
        Result result = null;
        if (rows > 0) {
            result = Result.ok(null);
        } else {
            Result.build(null, ResultCodeEnum.USERNAME_USED);
        }
        WebUtil.writeJson(resp, result);

    }

    /**
     * 接收用户登录的业务处理方法
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //接受用户名和密码
        SysUser sysUser = WebUtil.readJson(req, SysUser.class);
        SysUser loginUser = userService.findByUsername(sysUser.getUsername());
        Result result = Result.ok(null);;
        if (null == loginUser) {
            result = Result.build(null, ResultCodeEnum.USERNAME_USED);
        } else if (! MD5Util.encrypt(sysUser.getUser_pwd()).equals(loginUser.getUser_pwd())) {
            result=Result.build(null,ResultCodeEnum.PASSWORD_ERROR);
        }else {
            //登录成功 需要将用户的uid 和用户名相应个客户端
            Map hashMap = new HashMap<>();
            loginUser.setUser_pwd(" ");
            hashMap.put("loginUser", loginUser);
            result = Result.ok(hashMap);
        }
        WebUtil.writeJson(resp, result);
    }
}

